import axios from 'axios'
import { message } from 'ant-design-vue';
import { useRouter } from 'vue-router'
// 引入进度条
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
// 进度条配置项这样写
// NProgress.configure({
//   showSpinner: false
// });

let router = useRouter()
const isDev = process.env.NODE_ENV == 'development'
// 创建axios实例
// axios.defaults.headers.post["Content-Type"] =
//   "application/x-www-form-urlencoded;charset=UTF-8";
// axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
axios.defaults.baseURL = '/api/';
const request = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  // 超时
  timeout: 10000,
  //请求头设置
  headers: {
    // 'Content-Type': 'application/json;charset=utf-8',
    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
    'token': sessionStorage.getItem('token'),
  }
})
//请求拦截器
let preUrl = ''
request.interceptors.request.use(
  config => {
    if ((config.url + config.data) === preUrl) {
      return
    }
    if (config.data || config.url) {
      preUrl = config.url + config.data
    }
    setTimeout(() => {
      preUrl = ''
    }, 2000);
    // config.headers.token = sessionStorage.getItem('token') || '';
    // config.headers.authorization = sessionStorage.getItem('authorization') || ''
    NProgress.start();
    return config
  },
  error => {
    NProgress.start();
    Promise.reject(error)
  }
)
//响应拦截器
request.interceptors.response.use(
  res => {
    NProgress.done();
    let { state, msg } = res.data.meta
    if (state !== 200 && state != 201) {
      message.warning(msg)
      if (state == 403) {
        router.push({ path: '/index/home' })
      }
    }
    return res
  },
  error => {
    NProgress.done();
    return Promise.reject(error)
  }
)
export default request